package com.hxci.web.bean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.*;

public class  Conn {
    private String driver;
    private String url;
    private String dbuser;
    private String dbpwd;
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    public Conn(String realPath) {
        try {
        Properties properties=new Properties();
        File propFile=new File(realPath);
        properties.load(new FileReader(propFile));
        String driver=properties.get("jdbc.driver")+"";
        String url=properties.get("jdbc.url")+"";
        String user=properties.get("jdbc.user")+"";
        String password=properties.get("jdbc.password")+"";
        this.driver=driver;
        this.url=url;
        dbuser=user;
        dbpwd=password;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public List<Map>doQuery(String sql, List<Object> paramsList) {
        List<Map> list = new ArrayList<>();

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, dbuser, dbpwd);
            // 根据SQL语句类型创建PreparedStatement
            if (sql.trim().toLowerCase().startsWith("select")) {
                pstmt = conn.prepareStatement(sql);
                for (int i = 0; i < paramsList.size(); i++) {
                    pstmt.setObject(i + 1, paramsList.get(i));
                }
                rs = pstmt.executeQuery();
                ResultSetMetaData rsmd = rs.getMetaData();
                int colCount = rsmd.getColumnCount();

                while (rs.next()) {
                    Map<String, String> map = new HashMap<>();
                    for (int i = 1; i <= colCount; i++) {
                        String colName = rsmd.getColumnLabel(i);
                        String colValue = rs.getString(colName);
                        map.put(colName, colValue);
                    }
                    list.add(map);
                }
            } else {
                // 对于非SELECT语句，使用executeUpdate

                pstmt = conn.prepareStatement(sql);
                for (int i = 0; i < paramsList.size(); i++) {
                    pstmt.setObject(i + 1, paramsList.get(i));
                }
                int rowsAffected = pstmt.executeUpdate();
//                System.out.println((Collections.singletonMap("rowsAffected", String.valueOf(rowsAffected))));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return list;

        }
    }
}
